package com.qf.listener;

import com.qf.entity.Hotal;
import com.qf.service.ICtiyService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class RabbitMsgListener {


    @Autowired
    private ICtiyService ctiyService;

    /**
     * 保证MQ的消费方法幂等
     * @param hotal
     * @param channel
     * @param message
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    exchange = @Exchange(name = "hotal_exchange", type = "fanout"),
                    value = @Queue(name = "city_queue", durable = "true")
            )
    })
    public void msgHandler(Hotal hotal, Channel channel, Message message){
        System.out.println("城市服务接收到消息：" + hotal);
        //hotal.getId();
        //redis中 - 集合保存 - 判断

        //修改对应的城市的酒店数量
        ctiyService.updateHotalNumber(hotal.getCid(), 1);

        //手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
